import 'dart:convert';
import 'package:fast_gbk/fast_gbk.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sxw_bluetooth_provider/sxw_bluetooth_provider.dart';

import 'bluetooth_state_widget.dart';
import 'button_factory.dart';
import 'manage_device_page.dart';
import 'toast_error_handler.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return OKToast(
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  SxwBluetoothProvider provider = SxwBluetoothProvider();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          createIconButton(Icons.devices, _manageDevice),
        ],
      ),
      body: ListView(
        children: <Widget>[
          _createCurrentState(),
          createTextButton("模拟连接sxw-p051<ble>", () async {
            final config = PrinterBleConnectConfig(
              name: "sxw-p051",
            )..writeTransformer = PrinterTransformer();
            var device = await provider
                .connectBle(config)
                .catchError(ToastErrorHandler());
            listenReceive(device, gbk);
          }),
          createTextButton("模拟连接mac<ble>", () async {
            final config = MacTestConnectConfig(
              name: testMacName,
            )..writeTransformer = MacTestTransformer();
            var device = await provider
                .connectBle(config)
                .catchError(ToastErrorHandler());
            listenReceive(device);
          }),
          createTextButton("模拟连接sxw-p051<spp>", () async {
            final config = PrinterSppConfig("sxw-p051", "0000");
            final device = await provider
                .connectSpp(config)
                .catchError(ToastErrorHandler());
            listenReceive(device, gbk);
          }),
        ],
      ),
    );
  }

  void listenReceive(SxwBluetoothDevice device, [Encoding codec]) {
    if (device == null) {
      return;
    }
    device.receiveStream.listen((data) {
      String msg;
      if (codec != null) {
        msg = codec.decode(data);
      } else {
        msg = "$data";
      }
      onReceive(device, msg);
    });
  }

  void onReceive(SxwBluetoothDevice device, String msg) {
    showToast("收到了${device.name} 的消息:\n$msg".trim());
  }

  String get testMacName {
    if (Platform.isIOS) {
      return "Caijinglong的iMac";
    } else {
      return "使用mac模拟外设";
    }
  }

  Widget _createCurrentState() {
    return Column(
      children: <Widget>[
        Container(
          height: 200,
          child: BluetoothStateWidget(provider),
        ),
        Container(
          height: 1,
          color: Colors.black26,
        ),
      ],
    );
  }

  _manageDevice() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) => ManagerDevicePage(provider),
      ),
    );
  }
}
